
package com.efast.dmom.aps.service.impl;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.efast.dmom.aps.bean.ResultBean;
import com.efast.dmom.aps.bean.Shift;
import com.efast.dmom.aps.bean.ShiftItem;
import com.efast.dmom.aps.bean.WorkingCalendar;
import com.efast.dmom.aps.dao.WorkingCalendarDao;
import com.efast.dmom.aps.datahandlers.ShiftDataHandler;
import com.efast.dmom.aps.datahandlers.WorkCalendarDataHandler;
import com.efast.dmom.aps.datahandlers.WorkingCalendarShiftDataHandler;
import com.efast.dmom.aps.entity.ShiftEntity;
import com.efast.dmom.aps.entity.ShiftItemEntity;
import com.efast.dmom.aps.service.WorkingCalendarService;
import com.efast.dmom.aps.util.CommonConstants;

@Service
public class WorkingCalendarServiceImpl implements WorkingCalendarService {
	@Autowired
	private WorkingCalendarDao workingCalendarDao;

	@Autowired
	private WorkCalendarDataHandler workCalendarDataHandler;

	@Autowired
	private WorkingCalendarShiftDataHandler workingCalendarShiftDataHandler;

	// 班次handler
	@Autowired
	private ShiftDataHandler shiftDataHandler;

//批量新增日历
	@Override
	public ResultBean insertWorkingCalendar(WorkingCalendar workingCalendar) {
		ResultBean result = new ResultBean(true);

//		// 车间信息不能为空
//		if (workingCalendar.getWorkshop() == null || workingCalendar.getWorkshop() == "") {
//			result.setSuccess(false);
//			result.setMessage("未选中车间");
//			return result;
//		}
//		// 产线信息不能为空
//		if (workingCalendar.getLine() == null || workingCalendar.getLine() == "") {
//			result.setSuccess(false);
//			result.setMessage("未选中产线");
//			return result;
//		}
//
//		List<String> currentDateList = workingCalendar.getCurrentDateList();
//		// 判断list里面是否有数据
//		if (currentDateList == null || currentDateList.size() < 1) {
//			result.setSuccess(false);
//			result.setMessage("未选中日期");
//			return result;
//		}
//
//		workingCalendar.setCreationTime(TimeUtil.getLocalDateTime());
//		workingCalendar.setCreator(SpringWebUtils.getRequestUser());
//
//		// 当为工作日时
//		if (workingCalendar.getIsWorkday() == 1) {
//			// 保存选中日期的信息到日历表中
//
//			for (int i = 0; i < currentDateList.size(); i++) {
//				// 循环时间集合赋值到DateString
//				workingCalendar.setDateString(currentDateList.get(i));
//				// 调用新增日历方法进行新增
//				workingCalendar.setId(workingCalendar.getId() + i);
//				workingCalendarDao.insertWorkingCalendar(workingCalendar);
//				//
//
//				workingCalendar.setCalendarId(workingCalendar.getId());
//				// 保存日历id和班次id到日历关系表中
//				workingCalendar.setItemsId(workingCalendar.getItemsId() + i);
//				workingCalendarDao.insertShift(workingCalendar);
//			}
//
//			result.setMessage("新增日历和班次成功");
//
//		} else {
//			// 当为休息日时
//			for (int i = 0; i < currentDateList.size(); i++) {
//				// 循环时间集合赋值到DateString
//				workingCalendar.setDateString(currentDateList.get(i));
//				// 调用新增日历方法进行新增
//				workingCalendar.setId(workingCalendar.getId() + i);
//				workingCalendarDao.insertWorkingCalendar(workingCalendar);
//			}
//			result.setSuccess(true);
//			result.setMessage("新增日历成功");
//		}
		return result;
	}

	// 批量更新工作日历
	@Override
	public ResultBean updateWorkingCalendar(WorkingCalendar workingCalendar) {
		ResultBean result = new ResultBean(true);

		// 车间信息不能为空
//		if (workingCalendar.getWorkshop() == null || workingCalendar.getWorkshop() == "") {
//			result.setSuccess(false);
//			result.setMessage("未选中车间");
//			return result;
//		}
//		// 产线信息不能为空
//		if (workingCalendar.getLine() == null || workingCalendar.getLine() == "") {
//			result.setSuccess(false);
//			result.setMessage("未选中产线");
//			return result;
//		}
//
//		List<String> currentDateList = workingCalendar.getCurrentDateList();
//		// 判断list里面是否有数据
//		if (currentDateList == null || currentDateList.size() < 1) {
//			result.setSuccess(false);
//			result.setMessage("未选中日期");
//			return result;
//		}
//		workingCalendar.setLastModifiedTime(TimeUtil.getLocalDateTime());
//		workingCalendar.setLastModifier(SpringWebUtils.getRequestUser());

		return null;

	}

	// 查询指定月份下所有工作日历的数据
	@Override
	public ResultBean getworkCanlendarByMonth(WorkingCalendar workingCalendar) {
		ResultBean result = new ResultBean(true, "");
		// 判断车间信息不为空
//		if (workingCalendar.getWorkshop() != null || workingCalendar.getWorkshop() != "") {
//			// 判断产线不为空
//			if (workingCalendar.getLine() != null || workingCalendar.getLine() != "") {
//				List<WorkingCalendar> list = workingCalendarDao.getworkCanlendarByMonth(workingCalendar);
//				result.setObject(list);
//				result.setSuccess(true);
//				result.setMessage("查询成功");
//				return result;
//			} else {
//				result.setSuccess(false);
//				result.setMessage("未选中产线");
//				return result;
//			}
//		} else {
//			result.setSuccess(false);
//			result.setMessage("未选中车间");
		return result;
//		}

	}

	// 删除班次
	@Override
	public ResultBean deleteShift(WorkingCalendar workingCalendar) {
		ResultBean result = new ResultBean(true, "");
		// 车间信息不能为空
//		if (workingCalendar.getWorkshop() == null || workingCalendar.getWorkshop() == "") {
//			result.setSuccess(false);
//			result.setMessage("未选中车间");
//			return result;
//		}
//		// 产线信息不能为空
//		if (workingCalendar.getLine() == null || workingCalendar.getLine() == "") {
//			result.setSuccess(false);
//			result.setMessage("未选中产线");
//			return result;
//		}
//		// 日期不能为空
//		if (workingCalendar.getCurrentDate() == null) {
//			result.setSuccess(false);
//			result.setMessage("日期不能为空");
//			return result;
//
//		}
//		// 当前班次不为空
//		if (workingCalendar.getShiftId() == null) {
//			result.setSuccess(false);
//			result.setMessage("班次不能为空");
//			return result;
//		}
//
//		// 当班次数量小于等于1时，无法删除班次
//		int sum = workingCalendarDao.selectShiftSum(workingCalendar);
//		if (sum <= 1) {
//			result.setSuccess(false);
//			result.setMessage("一个工作日至少有一个班次，无法删除");
//			return result;
//		}
//
//		workingCalendarDao.deleteShift(workingCalendar);
//		result.setSuccess(true);
//		result.setMessage("删除成功");
		return result;
	}

	// 查询班次
	@Override
	public ResultBean selectShift(WorkingCalendar workingCalendar) {
		ResultBean result = new ResultBean(true, "");
		// 车间信息不能为空
//		if (workingCalendar.getWorkshop() == null || workingCalendar.getWorkshop() == "") {
//			result.setSuccess(false);
//			result.setMessage("未选中车间");
//			return result;
//		}
//		// 产线信息不能为空
//		if (workingCalendar.getLine() == null || workingCalendar.getLine() == "") {
//			result.setSuccess(false);
//			result.setMessage("未选中产线");
//			return result;
//		}
//		// 日期不能为空
//		if (workingCalendar.getCurrentDate() == null) {
//			result.setSuccess(false);
//			result.setMessage("日期不能为空");
//			return result;
//
//		}
//		Shift shift = workingCalendarDao.selectShift(workingCalendar);
//		result.setObject(shift);
//		result.setMessage("查询成功");
		return result;

	}

	// 获取数据 日历 =》班次集合 =》 班次详情
	@Override
	public Map<LocalDate, WorkingCalendar> getWorkingHoursPerDay(long plantId, long workshopId, long lineId,
			LocalDate startTime, LocalDate endTime) {
		Map<LocalDate, WorkingCalendar> getDate = new HashMap<LocalDate, WorkingCalendar>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("plantId", plantId);
		map.put("workshopId", workshopId);
		map.put("lineId", lineId);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		ShiftServiceImpl shiftServiceImpl = new ShiftServiceImpl();
		List<WorkingCalendar> workingHoursPerDay = workCalendarDataHandler.getWorkingHoursPerDay(map);
		if (workingHoursPerDay != null && workingHoursPerDay.size() > 0) {
			for (WorkingCalendar workingCalendar : workingHoursPerDay) {
				// 当getDate中存在此值时
				if (getDate.containsKey(workingCalendar.getCurrentDate())) {
					List<Shift> shiftList = getDate.get(workingCalendar.getCurrentDate()).getShiftList();
					if (shiftList.size() > 0) {
						for (Shift Shift : shiftList) {
							// 当getDate的shift集合中存在此集合名称时
							if (Shift.getInnnerData().getName().contains(workingCalendar.getShiftName())) {
								ShiftItem shiftItem = new ShiftItem();

								ShiftItemEntity shiftEntity = new ShiftItemEntity();
								shiftEntity.setName(workingCalendar.getShiftItemName());
								shiftEntity.setStartTime(workingCalendar.getShiftItemStartTime());
								shiftEntity.setEndTime(workingCalendar.getShiftItemEndTime());
								shiftEntity.setShiftItemSequence(workingCalendar.getShiftItemSequence());
								shiftEntity.setShiftItemType(workingCalendar.getShiftItemType());
								shiftItem.setInnerEntity(shiftEntity);
								if (CommonConstants.SHIFYITEMSEQUENSE.contains(workingCalendar.getShiftItemType())) {
									long timeCompare = shiftServiceImpl.timeCompare(
											workingCalendar.getShiftItemEndTime(),
											workingCalendar.getShiftItemStartTime());
									double count = timeCompare / 60d;
									Shift.setShiftTotal(Shift.getShiftTotal() + count);
									getDate.get(workingCalendar.getCurrentDate()).setTotalHours(
											count + getDate.get(workingCalendar.getCurrentDate()).getTotalHours());
									Shift.getShiftItems().add(shiftItem);
								}
							} else {
								// 当getDate中的shift集合中不存在此名称时，新增一个班次和item存入getDate对应日期
								Shift shift2 = new Shift();

								ShiftEntity entity2 = new ShiftEntity();
								entity2.setName(workingCalendar.getShiftName());
								entity2.setStartTime(workingCalendar.getStartTime());
								entity2.setEndTime(workingCalendar.getEndTime());

								shift2.setInnnerData(entity2);

								ShiftItem shiftItem = new ShiftItem();

								ShiftItemEntity shiftEntity = new ShiftItemEntity();
								shiftEntity.setName(workingCalendar.getShiftItemName());
								shiftEntity.setStartTime(workingCalendar.getShiftItemStartTime());
								shiftEntity.setEndTime(workingCalendar.getShiftItemEndTime());
								shiftEntity.setShiftItemSequence(workingCalendar.getShiftItemSequence());
								shiftEntity.setShiftItemType(workingCalendar.getShiftItemType());
								shiftItem.setInnerEntity(shiftEntity);
								// 当为工作时将所有班次有效时间和工作日历的有效时间存起来
								if (CommonConstants.SHIFYITEMSEQUENSE.contains(workingCalendar.getShiftItemType())) {
									long timeCompare = shiftServiceImpl.timeCompare(
											workingCalendar.getShiftItemEndTime(),
											workingCalendar.getShiftItemStartTime());
									double count = timeCompare / 60d;
									shift2.setShiftTotal(Shift.getShiftTotal() + count);
									getDate.get(workingCalendar.getCurrentDate()).setTotalHours(
											count + getDate.get(workingCalendar.getCurrentDate()).getTotalHours());
									shift2.getShiftItems().add(shiftItem);
									shiftList.add(shift2);
								}
							}
						}
					} else {
						Shift shift2 = new Shift();

						ShiftEntity entity2 = new ShiftEntity();
						entity2.setName(workingCalendar.getShiftName());
						entity2.setStartTime(workingCalendar.getStartTime());
						entity2.setEndTime(workingCalendar.getEndTime());

						shift2.setInnnerData(entity2);

						ShiftItem shiftItem = new ShiftItem();

						ShiftItemEntity shiftEntity = new ShiftItemEntity();
						shiftEntity.setName(workingCalendar.getShiftItemName());
						shiftEntity.setStartTime(workingCalendar.getShiftItemStartTime());
						shiftEntity.setEndTime(workingCalendar.getShiftItemEndTime());
						shiftEntity.setShiftItemSequence(workingCalendar.getShiftItemSequence());
						shiftEntity.setShiftItemType(workingCalendar.getShiftItemType());
						shiftItem.setInnerEntity(shiftEntity);
						// 当为工作时将所有班次有效时间和工作日历的有效时间存起来
						if (CommonConstants.SHIFYITEMSEQUENSE.contains(workingCalendar.getShiftItemType())) {
							long timeCompare = shiftServiceImpl.timeCompare(workingCalendar.getShiftItemEndTime(),
									workingCalendar.getShiftItemStartTime());
							double count = timeCompare / 60d;
							shift2.setShiftTotal(shift2.getShiftTotal() + count);
							getDate.get(workingCalendar.getCurrentDate()).setTotalHours(
									count + getDate.get(workingCalendar.getCurrentDate()).getTotalHours());
							shift2.getShiftItems().add(shiftItem);
							shiftList.add(shift2);
						}
					}
				} else {
					WorkingCalendar workingCalendar2 = new WorkingCalendar();
					workingCalendar2.setShiftList(new ArrayList<Shift>());

					Shift shift2 = new Shift();
					shift2.setShiftItems(new ArrayList<ShiftItem>());

					ShiftEntity entity2 = new ShiftEntity();
					entity2.setName(workingCalendar.getShiftName());
					entity2.setStartTime(workingCalendar.getStartTime());
					entity2.setEndTime(workingCalendar.getEndTime());

					shift2.setInnnerData(entity2);

					ShiftItem shiftItem = new ShiftItem();

					ShiftItemEntity shiftEntity = new ShiftItemEntity();
					shiftEntity.setName(workingCalendar.getShiftItemName());
					shiftEntity.setStartTime(workingCalendar.getShiftItemStartTime());
					shiftEntity.setEndTime(workingCalendar.getShiftItemEndTime());
					shiftEntity.setShiftItemSequence(workingCalendar.getShiftItemSequence());
					shiftEntity.setShiftItemType(workingCalendar.getShiftItemType());
					// 当为工作时将所有班次有效时间和工作日历的有效时间存起来
					if (CommonConstants.SHIFYITEMSEQUENSE.contains(workingCalendar.getShiftItemType())) {
						long timeCompare = shiftServiceImpl.timeCompare(workingCalendar.getShiftItemEndTime(),
								workingCalendar.getShiftItemStartTime());
						double count = timeCompare / 60d;
						shift2.setShiftTotal(shift2.getShiftTotal() + count);
						workingCalendar2.setTotalHours(count + workingCalendar.getTotalHours());
						shiftItem.setInnerEntity(shiftEntity);
						shift2.getShiftItems().add(shiftItem);
						workingCalendar2.getShiftList().add(shift2);
						getDate.put(workingCalendar.getCurrentDate(), workingCalendar2);
					}
				}
			}
		}
		return getDate;
	}

	@Override
	public List<WorkingCalendar> selectcalendarsAndSchedulingCount(WorkingCalendar workingCalendar) {
		List<WorkingCalendar> selectcalendarsAndSchedulingCount = workCalendarDataHandler
				.selectcalendarsAndSchedulingCount(workingCalendar);
		return selectcalendarsAndSchedulingCount;
	}

	@Override
	public List<Map<String, Object>> queryShiftInfoByCalendar(WorkingCalendar workingCalendar) {
		return workCalendarDataHandler.queryShiftInfoByCalendar(workingCalendar);
	}

	@Override
	public List<Map<String, Object>> querycalendarBystartDataEndData(Map<String, Object> map) {
		List<Map<String, Object>> workCalendarDataHandler2 = workCalendarDataHandler.workCalendarDataHandler(map);
		return workCalendarDataHandler2;
	}

	// dateTime升序排列
	public List<ShiftItem> sortDataTime(List<ShiftItem> list) {
		Collections.sort(list, new Comparator<ShiftItem>() {

			@Override
			public int compare(ShiftItem item1, ShiftItem item2) {
				int compareTo = item1.getInnerEntity().getStartTime().compareTo(item2.getInnerEntity().getStartTime());
				return compareTo;
			}

		});
		return list;
	}

	@Override
	public ResultBean updateCalendarStatus(Map<String, Object> map) {
		ResultBean result = new ResultBean(true);
		List<Map<String, Object>> querycalendarBystartDataEndData = workCalendarDataHandler
				.selectCalendarDataByCalendarDateList(map);
		Integer status = Integer.valueOf(map.get("dateType").toString());
		if (querycalendarBystartDataEndData.size() > 0) {
			// 当更改为休息状态时删除是否有对应关联数据
			if (status == 1) {
				workingCalendarShiftDataHandler
						.deleteCalendaeShiftRelByShiftIdCalendarId(querycalendarBystartDataEndData.get(0));
			}
			// 更新日历表工作状态
			workCalendarDataHandler.updateCalendarStatus(map);
			if (status == 0) {
				Integer shiftId = (Integer) map.get("shiftId");
				Integer shiftSequence = (Integer) map.get("shiftSequence");
				if (shiftId == null) {
					result.setSuccess(false);
					result.setMessage("请检查班次是否填写!");
					return result;
				}
				if (shiftSequence == null) {
					result.setSuccess(false);
					result.setMessage("请检查班次顺序是否填写!");
					return result;
				}
				List<Long> queryCalendarByPlantWorkshopLine = workCalendarDataHandler.queryCalendarByPlantWorkshopLine(map);
				map.put("list", queryCalendarByPlantWorkshopLine);
				workCalendarDataHandler.addCalendarShiftRel(map);
			}
		} else {
			if (status == 1) {
				// 新增日历数据
				workCalendarDataHandler.insertCalendarDatas(map);
			} else {
				Integer shiftId = (Integer) map.get("shiftId");
				Integer shiftSequence = (Integer) map.get("shiftSequence");
				if (shiftId == null) {
					result.setSuccess(false);
					result.setMessage("请检查班次是否填写!");
					return result;
				}
				if (shiftSequence == null) {
					result.setSuccess(false);
					result.setMessage("请检查班次顺序是否填写!");
					return result;
				}
				workCalendarDataHandler.insertCalendarDatas(map);
				List<Long> queryCalendarByPlantWorkshopLine = workCalendarDataHandler
						.queryCalendarByPlantWorkshopLine(map);
				map.put("list", queryCalendarByPlantWorkshopLine);
				workCalendarDataHandler.addCalendarShiftRel(map);

			}
		}
		return result;
	}

	public List<Shift> sort(List<Shift> sh) {
		Collections.sort(sh, new Comparator<Shift>() {

			@Override
			public int compare(Shift o1, Shift o2) {
				int compareTo = o1.getInnnerData().getStartTime().compareTo(o2.getInnnerData().getStartTime());
				return compareTo;
			}
		});
		return sh;
	}

	@Override
	public ResultBean addCalendarShiftRel(Map<String, Object> map) {
		ResultBean resultBean = new ResultBean(true);
		Map<String, Object> map2 = new HashMap<String, Object>();
		// 获取日历id
		List<Long> queryCalendarByPlantWorkshopLine = workCalendarDataHandler.queryCalendarByPlantWorkshopLine(map);
		map2.put("list", queryCalendarByPlantWorkshopLine);
		map2.put("shiftId", map.get("shiftId"));
		map2.put("shiftSequence", map.get("shiftSequence"));
		// 获取班次id
		List<Long> selectShiftIdByCalendarId = workingCalendarShiftDataHandler
				.selectShiftIdByCalendarId(queryCalendarByPlantWorkshopLine.get(0));
		if (selectShiftIdByCalendarId.contains(((Integer) map.get("shiftId")).longValue())) {
			resultBean.setSuccess(false);
			resultBean.setMessage("当前班次已存在，请添加其他班次！");
			return resultBean;
		}
		List<Integer> shiftSequenceList = workingCalendarShiftDataHandler.selectShiftSequenceByCalendarId(queryCalendarByPlantWorkshopLine.get(0));
		if (shiftSequenceList.contains((Integer) map.get("shiftSequence"))) {
			resultBean.setSuccess(false);
			resultBean.setMessage("班次顺序已存在，请重填！！");
			return resultBean;
		}
		selectShiftIdByCalendarId.add(((Integer) map.get("shiftId")).longValue());
		// queryCalendarByPlantWorkshopLine.add(((Integer)map.get("shiftId")).longValue());
		List<Long> arrayList = new ArrayList<Long>();
		arrayList.add(((Integer) map.get("shiftId")).longValue());
		arrayList.addAll(selectShiftIdByCalendarId);
		List<Shift> selectShiftByShiftId2 = shiftDataHandler.selectShiftByShiftId(arrayList);
		if (selectShiftByShiftId2 != null && selectShiftByShiftId2.size() > 1) {
			List<Shift> noSpan = new ArrayList<Shift>();
			List<Shift> span = new ArrayList<Shift>();
			for (Shift shift : selectShiftByShiftId2) {
				if (shift.getInnnerData().getDaySpan() == 0) {
					noSpan.add(shift);
				} else {
					span.add(shift);
				}
			}
			List<Shift> noSpan1 = sort(noSpan);
			List<Shift> span1 = sort(span);
			if (noSpan1.size() > 1) {
				for (int i = 1; i < noSpan1.size(); i++) {
					if (noSpan1.get(i).getInnnerData().getStartTime()
							.isBefore(noSpan1.get(i - 1).getInnnerData().getEndTime())) {
						resultBean.setSuccess(false);
						resultBean.setMessage("当前班次与已存在班次时间冲突！");
						return resultBean;
					}
				}
			}
			if (span1.size() > 1) {
				for (int i = 1; i < span1.size(); i++) {
					if (span1.get(i).getInnnerData().getStartTime()
							.isBefore(span1.get(i - 1).getInnnerData().getEndTime())) {
						resultBean.setSuccess(false);
						resultBean.setMessage("当前班次与已存在班次时间冲突！");
						return resultBean;
					}
				}
			}
			if (span1.size() == 1 && noSpan1.size() == 1) {
				List<Shift> shifts = new ArrayList<Shift>();
				shifts.add(span1.get(0));
				shifts.add(noSpan1.get(0));
				List<Shift> sort = sort(shifts);
				for (int i = 1; i < sort.size(); i++) {
					if (sort.get(i).getInnnerData().getStartTime()
							.isBefore(sort.get(i - 1).getInnnerData().getEndTime())) {
						resultBean.setSuccess(false);
						resultBean.setMessage("当前班次与已存在班次时间冲突！");
						return resultBean;
					}
				}
			}

		}
		workCalendarDataHandler.addCalendarShiftRel(map2);
		return resultBean;
	}

	@Override
	public void deleteCalendarShiftRel(Map<String, Object> map) {
		Map<String, Object> map2 = new HashMap<String, Object>();
		List<Long> queryCalendarByPlantWorkshopLine = workCalendarDataHandler.queryCalendarByPlantWorkshopLine(map);
		map2.put("calendarId", queryCalendarByPlantWorkshopLine.get(0));
		map2.put("shiftId", map.get("shiftId"));
		workCalendarDataHandler.deleteCalendarShiftRel(map2);
	}
}
